/*
 * @Author: your name
 * @Date: 2020-01-01 19:15:22
 * @LastEditTime : 2020-01-11 12:15:52
 * @LastEditors  : Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \vhr_dev\src\store\index.js
 */
import Vue from 'vue'
import Vuex from 'vuex'
import { Notification } from 'element-ui';
import {getRequest} from "../utils/api";
import '../utils/stomp'
import '../utils/sockjs'

Vue.use(Vuex)

const now = new Date();

const store = new Vuex.Store({
    state: {
        routes: [],
        sessions: {},
        hrs: [],
        currentSession: null,
        currentHr: JSON.parse(window.sessionStorage.getItem("user")),
        filterKey: '',
        stomp: null,
        isDot: {},
        visitedViews: [],
        cachedViews: []
    },
    mutations: {
        INIT_CURRENTHR(state, hr) {
            state.currentHr = hr;
        },
        initRoutes(state, data) {
            state.routes = data;
        },
        changeCurrentSession(state, currentSession) {
            Vue.set(state.isDot, state.currentHr.username + '#' + currentSession.username, false);
            state.currentSession = currentSession;
        },
        addMessage(state, msg) {
            let mss = state.sessions[state.currentHr.username + '#' + msg.to];
            if (!mss) {
                // state.sessions[state.currentHr.username+'#'+msg.to] = [];
                Vue.set(state.sessions, state.currentHr.username + '#' + msg.to, []);
            }
            state.sessions[state.currentHr.username + '#' + msg.to].push({
                content: msg.content,
                date: new Date(),
                self: !msg.notSelf
            })
        },
        INIT_DATA(state) {
            //浏览器本地的历史聊天记录可以在这里完成
            let data = localStorage.getItem('vue-chat-session');
            if (data) {
                state.sessions = JSON.parse(data);
            }
        },
        INIT_HR(state, data) {
            state.hrs = data;
        },
        // 头部选项卡开始 代码
        ADD_VISITED_VIEWS: (state, view) => {
            if(view.name == 'Home') return
            if (state.visitedViews.some(v => v.path === view.fullPath)) return
            state.visitedViews.push({
              name: view.name,
              path: view.fullPath,
              title: view.name || 'no-name'
            })
            if (!view.meta.noCache) {
              state.cachedViews.push(view.name)
            }
          },
          DEL_VISITED_VIEWS: (state, view) => {
            for (const [i, v] of state.visitedViews.entries()) {
              if (v.path === view.path) {
                state.visitedViews.splice(i, 1)
                break
              }
            }
            for (const i of state.cachedViews) {
              if (i === view.name) {
                const index = state.cachedViews.indexOf(i)
                state.cachedViews.splice(index, 1)
                break
              }
            }
          },
          DEL_VISITED_VIEWS_TOGO: (state, view) => {
            for (const [i, v] of state.visitedViews.entries()) {
              if (v.path === view.fullPath) {
                state.visitedViews.splice(i, 1)
                break
              }
            }
            for (const i of state.cachedViews) {
              if (i === view.name) {
                const index = state.cachedViews.indexOf(i)
                state.cachedViews.splice(index, 1)
                break
              }
            }
          },
          DEL_OTHERS_VIEWS: (state, view) => {
            for (const [i, v] of state.visitedViews.entries()) {
              if (v.path === view.path) {
                state.visitedViews = state.visitedViews.slice(i, i + 1)
                break
              }
            }
            for (const i of state.cachedViews) {
              if (i === view.name) {
                const index = state.cachedViews.indexOf(i)
                state.cachedViews = state.cachedViews.slice(index, i + 1)
                break
              }
            }
          },
          DEL_ALL_VIEWS: (state) => {
            state.visitedViews = []
            state.cachedViews = []
          }
        //   选项卡结束代码
    },
    actions: {
        // 选项卡开始
        addVisitedViews({ commit }, view) {
            commit('ADD_VISITED_VIEWS', view)
          },
          delVisitedViews({ commit, state }, view) {
            return new Promise((resolve) => {
              commit('DEL_VISITED_VIEWS', view)
              resolve([...state.visitedViews])
            })
          },
          // 自定义一个删除 
          delVisitedViewstogo({ commit, state }, view) {
            return new Promise((resolve) => {
              commit('DEL_VISITED_VIEWS_TOGO', view)
              resolve([...state.visitedViews])
            })
          },
          delOthersViews({ commit, state }, view) {
            return new Promise((resolve) => {
              commit('DEL_OTHERS_VIEWS', view)
              resolve([...state.visitedViews])
            })
          },
          delAllViews({ commit, state }) {
            return new Promise((resolve) => {
              commit('DEL_ALL_VIEWS')
              resolve([...state.visitedViews])
            })
          },
        // 选项卡结束
        connect(context) {
            // context.state.stomp = Stomp.over(new SockJS('/ws/ep'));
            // context.state.stomp.connect({}, success => {
            //     context.state.stomp.subscribe('/user/queue/chat', msg => {
            //         let receiveMsg = JSON.parse(msg.body);
            //         if (!context.state.currentSession || receiveMsg.from != context.state.currentSession.username) {
            //             Notification.info({
            //                 title: '【' + receiveMsg.fromNickname + '】发来一条消息',
            //                 message: receiveMsg.content.length > 10 ? receiveMsg.content.substr(0, 10) : receiveMsg.content,
            //                 position: 'bottom-right'
            //             })
            //             Vue.set(context.state.isDot, context.state.currentHr.username + '#' + receiveMsg.from, true);
            //         }
            //         receiveMsg.notSelf = true;
            //         receiveMsg.to = receiveMsg.from;
            //         context.commit('addMessage', receiveMsg);
            //     })
            // }, error => {

            // })
        },
        initData(context) {
            context.commit('INIT_DATA')
            getRequest("/chat/hrs").then(resp => {
                if (resp) {
                    context.commit('INIT_HR', resp);
                }
            })
        }
    }
})

store.watch(function (state) {
    return state.sessions
}, function (val) {
    localStorage.setItem('vue-chat-session', JSON.stringify(val));
}, {
    deep: true/*这个貌似是开启watch监测的判断,官方说明也比较模糊*/
})


export default store;